package jsyf.oa.service.psi;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jsyf.com.util.FastJsonConvert;
import jsyf.oa.dao.attach.AttachDao;
import jsyf.oa.dao.attach.AttachModuleDao;
import jsyf.oa.dao.psi.GoodsDao;
import jsyf.oa.dao.psi.RepoInOutDao;
import jsyf.oa.dao.system.UserDao;
import jsyf.oa.entity.attach.AttachModuleEntity;
import jsyf.oa.entity.attach.AttachmentEntity;
import jsyf.oa.entity.psi.GoodsEntity;
import jsyf.oa.entity.psi.PsiEntity;
import jsyf.oa.entity.psi.RepoInOutMainEntity;
import jsyf.oa.facade.psi.GoodsFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by Maqiuqiu on 2018/10/17.
 */
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class GoodsService implements GoodsFacade {
    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private RepoInOutDao repoInOutDao;

    @Autowired
    private AttachModuleDao attachModuleDao;
    @Autowired
    private AttachDao attachDao;
    @Autowired
    private UserDao userDao;

    @Override
    public String save(String jsonData) {
//        JSONObject json = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
//        GoodsEntity entity = JSON.parseObject(json.getString("main"), GoodsEntity.class);
        PsiEntity psiEntity = JSON.toJavaObject(JSON.parseObject(jsonData), PsiEntity.class);
        GoodsEntity entity = psiEntity.getMain();
        Integer rows;
        if ("0".equals(entity.getId()) || StringUtils.isBlank(entity.getId())) {
            rows = goodsDao.add(entity);
        } else {
            GoodsEntity goodsEntity = (GoodsEntity) goodsDao.getIBaseEntityById(entity.getId());
            goodsEntity.setName(entity.getName());
            goodsEntity.setUnit(entity.getUnit());
            goodsEntity.setSpec(entity.getSpec());
            goodsEntity.setUnitPrice(entity.getUnitPrice());
            goodsEntity.setDescription(entity.getDescription());
            goodsEntity.setImage(entity.getImage());
            goodsEntity.setExtra(entity.getExtra());
            goodsEntity.setExtraInfo(entity.getExtraInfo());
            goodsEntity.setRemark(entity.getRemark());
            goodsEntity.setCreateUserId(entity.getCreateUserId());
            goodsEntity.setCreateTime(entity.getCreateTime());
            goodsEntity.setUpdateUserId(entity.getUpdateUserId());
            goodsEntity.setUpdateTime(entity.getUpdateTime());
            rows = goodsDao.update(goodsEntity);
        }
        String mainId = entity.getId();
        //保存附件
        attachModuleDao.removeByCondition(" AND MODULE_ID = ? ", new String[]{mainId});
        //添加
        List<AttachmentEntity> attachmentEntityList = psiEntity.getAttaches();
        if (attachmentEntityList != null && attachmentEntityList.size() > 0) {
            for (AttachmentEntity attach : attachmentEntityList) {
                AttachModuleEntity attachModuleEntity = new AttachModuleEntity();
                attachModuleEntity.setAttachId(attach.getId());
                attachModuleEntity.setAttachModule(10);
                attachModuleEntity.setModuleId(mainId);
                attachModuleDao.add(attachModuleEntity);
                attachModuleDao.addAttach(attach.getId());
            }
        }
        return rows == 0 ? "" : entity.getId();
    }

    @Override
    public Boolean delById(String id) {
        return goodsDao.delById(id) > 0;
    }

    @Override
    public Boolean removeById(String id) {
        return goodsDao.removeById(id) > 0;
    }

    @Override
    public JSONObject getGoodsList(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String companyId = jsonParams.getString("companyId");
        String key = jsonParams.getString("key");
        //分页信息
        int requestPage = 1;
        int pageSize = Integer.MAX_VALUE;
        if (jsonParams.containsKey("pageSize")) {
            pageSize = jsonParams.getInteger("pageSize");
        }
        if (jsonParams.containsKey("requestPage")) {
            requestPage = jsonParams.getInteger("requestPage");
        }
        //传参
        StringBuffer condition = new StringBuffer();
        if (!StringUtils.isBlank(companyId)) {
            condition.append(" AND t_sys_company.ID = '" + companyId + "' ");
        }
        if (!StringUtils.isBlank(key)) {
            condition.append(" AND t_psi_goods.`NAME` LIKE '%" + key + "%' ");
        }
        condition.append(" ORDER BY t_psi_goods.CREATE_TIME DESC");
        //查询list
        List<JSONObject> records = goodsDao.getGoodsList(condition.toString(), requestPage, pageSize);
        //查询总数
        int recordCount = goodsDao.getGoodsList(condition.toString(), 1, Integer.MAX_VALUE).size();
        //如果整除表示正好分N页，如果不能整除在N页的基础上+1页
        int pageCount = recordCount % pageSize == 0 ? recordCount / pageSize : (recordCount / pageSize) + 1;
        //存放分页信息
        JSONObject sendData = new JSONObject();
        //存放list
        JSONObject result = new JSONObject();
        sendData.put("recordCount", recordCount);
        sendData.put("pageCount", pageCount);
        sendData.put("requestPage", 1);
        result.put("pager", sendData);
        //子数组对象
        result.put("records", records);
        return result;
    }

    @Override
    public JSONObject getGoodsById(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        JSONObject results = new JSONObject();
        String id = jsonParams.getString("id");
        JSONObject result = goodsDao.getJSONById(id);
        JSONObject jsonObject = userDao.getJSONById(result.getString("createUserId"));
        String createUserName = jsonObject.getString("name");
        result.put("createUserName",createUserName);
        results.put("main", result);
        return results;
    }

    @Override
    public JSONObject getInventoryGoodsInfoByGoodsId(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        JSONObject results = new JSONObject();
        List<JSONObject>  outRepoData = new ArrayList<>();
        String goodsId = jsonParams.getString("goodsId");
        JSONObject result = goodsDao.getInventoryGoodsInfo(goodsId);
        List<RepoInOutMainEntity> list =
                repoInOutDao.getEntityListByCondition("AND GOODS_ID = ? AND AUDIT_FLAG = '1' AND IN_OUT_FLAG = '0' ORDER BY DATE DESC",new Object[]{goodsId});
        for (int i = 0; i < list.size(); i++) {
            RepoInOutMainEntity entity = list.get(i);
            List<AttachModuleEntity> attachModuleEntities =
                    attachModuleDao.getEntityListByCondition("AND MODULE_ID = ? ",new Object[]{entity.getId()});
            for (int j = 0; j < attachModuleEntities.size(); j++) {
                AttachModuleEntity attachModuleEntity = attachModuleEntities.get(j);
                JSONObject jsonObject = attachDao.getJSONById(attachModuleEntity.getAttachId());
                JSONObject sendData = new JSONObject();
                sendData.put("url",jsonObject.getString("url"));
                sendData.put("name",jsonObject.getString("name"));

                sendData.put("outRepoDate",entity.getDate());
                sendData.put("outUserName",entity.getOutUserName());
                sendData.put("outCount",entity.getCount());
                sendData.put("receiveUserName",entity.getReceiveUserName());
                sendData.put("remark",entity.getRemark());
                outRepoData.add(sendData);
            }
        }
        results.put("main", result);
        results.put("outRepoList", outRepoData);
        return results;
    }

    @Override
    public List<JSONObject> getGoodsInfoByName(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String key = jsonParams.getString("key");
        String userId = jsonParams.getString("createUserId");
        List<JSONObject> objectList =
                goodsDao.getGoodsInfoByName(" AND t_psi_goods.`NAME` like ? AND t_psi_goods.CREATE_USER_ID = ?", new Object[]{"%" + key + "%",userId});
        return objectList;
    }
}
